package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var wg = sync.WaitGroup{}

func SetNum(chan1 chan int) {
	defer wg.Done()
	// defer close(chan1)

	for {
		// 初始化随机数生成器
		rand.Seed(time.Now().UnixNano())
		// 生成一个大于1的随机整数
		randomNumber := rand.Intn(100) + 2
		chan1 <- randomNumber
		fmt.Printf("存：%v ", randomNumber)
		time.Sleep(time.Second * 1)
	}
}

func Square(chan1 chan int, chan2 chan int) {
	defer wg.Done()
	// defer close(chan2)
	for {
		x, ok := <-chan1
		if !ok {
			break
		}

		sum := 0
		for {
			sum += x % 10
			x = x / 10
			if x == 0 {

				break
			}

		}

		chan2 <- sum
		time.Sleep(time.Second * 1)
	}
}

func GetNum(chan2 chan int) {
	defer wg.Done()
	for {
		x, ok := <-chan2
		if !ok {
			break
		}
		fmt.Printf("取：%v ", x)
		time.Sleep(time.Second * 1)
	}
}

func main() {
	st := int(time.Now().Unix())
	var chan1 chan int = make(chan int, 1)
	var chan2 chan int = make(chan int, 1)
	wg.Add(7)
	go SetNum(chan1)
	for i := 1; i <= 5; i++ {
		go Square(chan1, chan2)
	}
	go GetNum(chan2)
	fmt.Printf("\n")
	wg.Wait()
	fmt.Println("use_time：", int(time.Now().Unix())-st)

}
